﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;

namespace RM.Entities.Data
{
    public class DataManager
    {
        public static ISessionFactory SessionFactory = CreateSessionFactory();

        public void SetupDB()
        {
            ISessionFactory sessionFactory = CreateSessionFactoryForDBSetup();

            sessionFactory.Close();
            sessionFactory.Dispose();
        }


        private static ISessionFactory CreateSessionFactory()
        {
            try
            {
                Assembly entityMapAssembly = Assembly.LoadFrom(System.AppDomain.CurrentDomain.BaseDirectory + "bin\\RM.Entities.Data.dll");

                return Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DevDB")))
                    .Mappings(m => m.FluentMappings.AddFromAssembly(entityMapAssembly))
                    //.ExposeConfiguration(BuildSchema)
                    .BuildSessionFactory();

            }
            catch
            {
                return null;
                
            }
        }

        private static ISessionFactory CreateSessionFactoryForDBSetup()
        {
            Assembly entityMapAssembly = Assembly.LoadFrom(System.AppDomain.CurrentDomain.BaseDirectory + "RM.Entities.Data.dll");

            return Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DevDB")))
                .Mappings(m => m.FluentMappings.AddFromAssembly(entityMapAssembly))
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
        }

        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(false, true);
        }
    }
}
